package com.sxbbc.common.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.core.entity.jz.BBusiness;
import com.sxbbc.common.core.entity.jz.ProcBrandInfo;
import com.sxbbc.common.core.enums.BrandTypeEnums;
import com.sxbbc.common.core.mapper.jz.BBusinessMapper;
import com.sxbbc.common.core.mapper.jz.ProcBrandInfoMapper;
import com.sxbbc.common.core.service.IProcBrandInfoService;
import com.sxbbc.common.core.utils.BasePage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 产品品牌信息表 服务实现类
 * </p>
 *
 * @author leehao
 * @since 2019-05-06
 */
@Service
public class ProcBrandInfoServiceImpl extends ServiceImpl<ProcBrandInfoMapper, ProcBrandInfo> implements IProcBrandInfoService {

    @Autowired
    private BBusinessMapper businessMapper;

    @Override
    public Page<ProcBrandInfo> queryBrandList(BasePage<ProcBrandInfo> page, ProcBrandInfo brandInfo) {
        QueryWrapper<ProcBrandInfo> wrapper = queryWrapper(brandInfo);
        wrapper.orderByDesc("sort");
        if (page.isPaging()) {
            super.page(page, wrapper);
        } else {
            List<ProcBrandInfo> list = super.list(wrapper);
            page.setRecords(list);
        }
        CalcuUtils cal = CalcuUtils.getInstance();
        for (ProcBrandInfo b : page.getRecords()) {
            // 需设置业务产品品牌
            if (cal.isEquals(b.getType(), BrandTypeEnums.BUSINESS.getId())) {
                BBusiness business = businessMapper.selectById(b.getTargetId());
                if (business != null) {
                    b.setTargetName(BrandTypeEnums.getName(b.getType()) + " " + business.getNickName());
                }
            }
        }
        return page;
    }

    /**
     * 品牌管理 共用查询条件
     *
     * @param brandInfo 查询条件
     * @return EntityWrapper查询对象
     * @author leehao
     */
    private QueryWrapper<ProcBrandInfo> queryWrapper(ProcBrandInfo brandInfo) {
        QueryWrapper<ProcBrandInfo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(brandInfo.getName())) {
            wrapper.eq("name", brandInfo.getName());
        }
        if (brandInfo.getTargetId() != null && brandInfo.getTargetId() != 0) {
            wrapper.eq("target_id", brandInfo.getTargetId());
        }
        return wrapper;
    }
}
